import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateSubCategoryDto, DeleteSubCategoryDto, EditSubCategoryDto, FindSubAllDto } from './dto/sub-category.dto';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class SubCategoryService {
  constructor(
    private readonly prismaService: PrismaService,
  ) { }
  async create(cscd: CreateSubCategoryDto) {
    
    const findOne = await this.prismaService.subCategory.findFirst({
      where: { title: cscd.title, userId: cscd.userId,parentCatId: cscd.parentCatId }
    })
    if (findOne) {
      throw new HttpException('类别已存在', HttpStatus.BAD_REQUEST)
    }
    try {
      await this.prismaService.subCategory.create({ data: { ...cscd } })
      return "类别添加成功"
    } catch (error) {
      throw new HttpException('类别添加失败', HttpStatus.BAD_REQUEST)
    }
  }

  async findSubAll(fsad: FindSubAllDto) {
    try {
      const res = await this.prismaService.subCategory.findMany({
        where: { userId: fsad.userId, level: fsad.level, isDelete: false, parentCatId: fsad.parentCatId },
      });
      return res
    } catch (error) {
      throw new HttpException('类别查找失败', HttpStatus.BAD_REQUEST)
    }
  }

  async edit(escd: EditSubCategoryDto) {
    try {
      await this.prismaService.subCategory.update({ where: { id: escd.id }, data: { ...escd } })
      return "类别编辑成功"
    } catch (error) {
      throw new HttpException('类别编辑失败', HttpStatus.BAD_REQUEST)
    }
  }

   async delete(dscd: DeleteSubCategoryDto) {
      // 判断是否有child
      const hasChild = await this.prismaService.subCategory.findUnique({
        where: { id: dscd.id },
        include: {
          _count: { select: { children: true } } // 仅计数不返回数据
        }
      });
      if ((hasChild?._count?.children ?? 0) > 0) {
        throw new HttpException('类别删除失败,该类别下存在子类别', HttpStatus.BAD_REQUEST)
      }
      try {
        await this.prismaService.subCategory.delete({ where: { id: dscd.id } })
        return "类别删除成功"
      } catch (error) {
        throw new HttpException('类别删除失败', HttpStatus.BAD_REQUEST)
      }
    }
}
